package springIOC.IOC_XML.handler;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class ResultSetUtil {

    public <T> T resultSetToBean(Class<T> tClass , ResultSet set) throws SQLException{
        T obj=null;
        Field field= null;
        try {
            obj=tClass.getDeclaredConstructor().newInstance();
            ResultSetMetaData data=set.getMetaData();
            int columnCount=data.getColumnCount();
            for(int i=1;i<=columnCount;i++){
                String columnName=data.getColumnName(i);
//                System.out.println("handler注入bean   columnName:"+columnName);
                try {

                    field = tClass.getDeclaredField(columnName);
                } catch (NoSuchFieldException e) {
//                    e.printStackTrace();
                    field= null;
                }
                if(field==null){
//                    System.out.println("bean对象中没有对应的字段，跳过");
//                    System.out.println("--------------------------------------------");
                    continue;
                }

                Object value=set.getObject(i);
                Method method=tClass.getMethod("set"+columnName.substring(0,1).toUpperCase()+columnName.substring(1),field.getType());
                method.invoke(obj,value);
//                System.out.println("注入成功");
//                System.out.println("----------------------------------------------------------------");
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
            System.out.println(field.getName()+"有属性却没有对应的公开的set方法，封装失败");
//            throw new SQLException(e);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
